import random

from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response

from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from meiduo_mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
import logging

from meiduo_mall.utils.yuntongxun.sms import CCP
from verifications.serializers import ImageCodeCheckSerializer
from . import constants
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.


logger = logging.getLogger('django')


class ImageCodeView(APIView):
    """
    获取验证码
    get:
    获取验证码
    """

    # url 路径:  GET /image_codes/(?P<image_code_id>[\w-]+)/
    def get(self, request, image_code_id):
        # 1 获取参数

        # 2 检验参数

        # 3 生成验证码
        text, image = captcha.generate_captcha()

        # 4 保存验证码
        # django_redis 提供了 get_redis_connection 方法 调用这个方法传递redis的配置名称,可获取到redis的连接对象, 通过redis连接对象可以执行redis命令
        redis_conn = get_redis_connection('verify_codes')

        # 保存到配置的redis数据库中
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 5 返回验证码

        return HttpResponse(image, content_type="image/jpg")


# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
class SMSCodeView(GenericAPIView):
    """
    短信验证码
    """

    serializer_class = ImageCodeCheckSerializer

    def get(self, request, mobile):
        """
        短信验证码
        :param request:
        :param mobile:
        :return:
        """
        # 1 先校验图片验证码,是否过期,正确
        s = self.get_serializer(data=request.query_params)
        s.is_valid(raise_exception=True)

        # 2 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 3 把生成的短信验证码保存到redis中, 设置过期时间, 六十秒内不能在生成短信验证码

        redis_conn = get_redis_connection('verify_codes')
        # 生成的短信验证码保存到redis中
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # redis_conn.setex('send_flag_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, 1)


        # redis管道
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, 1)

        # 让管道通知redis执行命令
        pl.execute()

        print('短信验证码: %s' % sms_code)

        # # 4 发送短信
        # try:
        #     # # 生成一个ccp对象
        #     ccp = CCP()
        #     # # 有效时间
        #     expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        #     result = ccp.send_template_sms(mobile, [sms_code, expires], constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送短信验证码[异常] [mobile: %s, message: %s]" % (mobile, e))
        #     return Response({"message": "failed"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        #
        # # 5 return 发送结果
        # else:
        #     if result == 0:
        #         # 返回0 表示发送短信成功
        #         logger.info("发送短信验证码[正常][mobile: %s]" % mobile)
        #         return Response({"message": "OK"}, status=status.HTTP_200_OK)
        #     else:
        #         # 返回-1 表示发送失败
        #         logger.info("发送短信验证码[异常][mobile: %s]" % mobile)
        #         return Response({"message": "failed"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        send_sms_code.delay(mobile, sms_code, expires, constants.SMS_CODE_TEMP_ID)

        return Response({"message": "OK"})
